package com.sign2024.sign2024project.projectservice.controller;

import com.alibaba.excel.EasyExcel;
import com.sign2024.sign2024core.common.CommonResult;
import com.sign2024.sign2024core.common.annotation.Log;
import com.sign2024.sign2024core.common.constants.CommonConstants;
import com.sign2024.sign2024core.common.exeception.CommonException;
import com.sign2024.sign2024core.entry.projectservice.SpecialistInfo;
import com.sign2024.sign2024core.entry.projecttask.ProjectTask;
import com.sign2024.sign2024project.aop.listener.SpecialistInfoListener;
import com.sign2024.sign2024project.projectservice.mapper.SpecialistInfoMapper;
import com.sign2024.sign2024project.projecttask.service.ProjectTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 专家信息表 控制层
 *
 * @author yujie
 * @data 2024/8/1 16:55
 */
@Api(tags = "工程服务")
@RestController
@RequestMapping("/api/specialistInfo")
public class SpecialistInfoController {

    @Resource
    private SpecialistInfoMapper specialistInfoMapper;

    @Resource
    private ProjectTaskService projectTaskService;

    @Log(title = "工程服务", businessType = "导入")
    @ApiOperation(value = "专家信息表excel导入", notes = "专家信息表excel导入")
    @Transactional
    @PostMapping("/import")
    public CommonResult<SpecialistInfo> importInfo(MultipartFile file, Integer taskId) {

        // 清空原有数据
        specialistInfoMapper.cleanSpecialistInfo();
        SpecialistInfoListener listener = new SpecialistInfoListener();
        try {
            EasyExcel.read(file.getInputStream(), listener).head(SpecialistInfo.class).sheet().headRowNumber(2).doReadSync();

            // 导入数据后， 将任务中的 专家信息表导入 列修改为 已导入
            ProjectTask projectTask = new ProjectTask();
            projectTask.setId(taskId);
            projectTask.setSpecialistInfo("已导入");
            projectTaskService.updateTask(projectTask);

            return CommonResult.success();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommonException(CommonConstants.ERROR, "excel导入失败");
        }
    }
}
